package com.wonders.common.parse.jaxb.adapter;

import javax.xml.bind.DatatypeConverter;
import javax.xml.bind.annotation.adapters.XmlAdapter;

/**
 * 字节CDATA适配器
 * 
 * @author WuBin
 * 
 */
public class ByteArrayCDATAAdapter extends XmlAdapter<String, byte[]> {

	public static final String cdataPrefix = "<![CDATA[";

	public static final String cdataPostFix = "]]>";

	public static final Integer subIndex = cdataPrefix.length();

	@Override
	public String marshal(byte[] value) throws Exception {

		String xml = DatatypeConverter.printBase64Binary(value);
		StringBuilder sb = new StringBuilder(cdataPrefix);
		sb.append(xml).append(cdataPostFix);

		return sb.toString();
	}

	@Override
	public byte[] unmarshal(String data) throws Exception {
		String base64 = data;
		if (data.startsWith(cdataPrefix)) {
			base64 = data.substring(subIndex);
			int tailIndex = base64.lastIndexOf(cdataPostFix);
			base64 = base64.substring(0, tailIndex);
		}
		return DatatypeConverter.parseBase64Binary(base64);
	}

}